﻿using System;
using SimpleServiceBus.Bus.MessageManagement.MessageHandling;
using SimpleServiceBus.Bus.Pipeline;
using SimpleServiceBus.EndpointManagement.Server.Utilities;
using SimpleServiceBus.Messages.Management.Monitoring;
using SimpleServiceBus.Persistence.Domain.Management.Entities;
using SimpleServiceBus.Persistence.Domain.Management.Repositories;
using SimpleServiceBus.Utilities;
using SimpleServiceBus.Utilities.Email;

namespace SimpleServiceBus.EndpointManagement.Server.MessageHandlers
{
    public class EndpointErrorMessageHandler : IMessageHandler<EndpointErrorNotification>
    {
        private static readonly ExceptionNotificationGoverner ErrorGoverner = new ExceptionNotificationGoverner();
        
        public void Handle(EndpointErrorNotification message, IMessageContext context)
        {
            string emailAddress = null;

            var endpointRepository = context.GetLocalService<IManagedEndpointRepository>();
            var emailer = context.GetLocalService<IEmailService>();

            if (emailer == null)
                return;

            if (endpointRepository != null)
            {
                ManagedEndpoint endpoint = endpointRepository.GetByEndpointId(message.EndpointID);
                if (endpoint != null && !String.IsNullOrEmpty(endpoint.SupportEmailAddress))
                    emailAddress = endpoint.SupportEmailAddress;

            }

            if (emailAddress == null)
                emailAddress = context.EndpointMetadata.SupportEmailAddress;

            if (emailAddress.IsNonEmpty())
                ErrorGoverner.SubmitErrorNotification(emailAddress, message, emailer);
        }
       
    }
}